package cn.kdyzm.service;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

/**
 * @author kdyzm
 * @date 2025/9/24
 */
@Service
public class UserService {

    private static final String CACHE_NAME = "users";

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class User {
        private Long id;
        private String name;
    }

    @Cacheable(value = CACHE_NAME, key = "#id", unless = "#result == null")
    public User getUserById(Long id) {
        System.out.println("从数据库查询用户: " + id);
        return new User(id, "用户");
    }

    /**
     * 更新操作 - 清除缓存
     */
    @CacheEvict(value = CACHE_NAME, key = "#user.id")
    public User updateUser(User user) {
        System.out.println("更新用户并清除缓存: " + user.getId());
        return user;
    }

    /**
     * 删除操作 - 清除缓存
     */
    @CacheEvict(value = CACHE_NAME, key = "#id")
    public void deleteUser(Long id) {
        System.out.println("删除用户并清除缓存: " + id);
    }

}
